<template>
  <view class="container">
    <!-- 爱心动画层 -->
    <view class="heart-animation-layer" v-if="showHearts">
      <view 
        v-for="(heart, index) in floatingHearts" 
        :key="'heart-' + index"
        class="floating-heart"
        :class="heart.type"
        :style="{
          left: heart.x + 'px',
          top: heart.y + 'px',
          fontSize: heart.size + 'px',
          color: heart.color,
          animationDelay: heart.delay + 's',
          animationDuration: heart.duration + 's'
        }"
      >
        {{ heart.symbol }}
      </view>
    </view>
    
    <view class="header">
      <text class="title">✨ 我们的美好时光 ✨</text>
      <text class="subtitle">爱与温馨的每一天</text>
    </view>
    
    <view class="cards">
      <!-- 恋爱纪念日 -->
      <view class="card love-card" @click="showLoveAnimation">
        <view class="card-header">
          <text class="icon">💕</text>
          <text class="card-title">恋爱纪念日</text>
        </view>
        <view class="card-content">
          <text class="date">{{ formatLoveStartDate }}</text>
          <text class="label">我们在一起已经</text>
          <view class="time-row">
            <view class="time-item">
              <text class="time-value">{{ loveTimeDuration.days }}</text>
              <text class="time-unit">天</text>
            </view>
            <view class="time-item">
              <text class="time-value">{{ loveTimeDuration.hours }}</text>
              <text class="time-unit">时</text>
            </view>
            <view class="time-item">
              <text class="time-value">{{ loveTimeDuration.minutes }}</text>
              <text class="time-unit">分</text>
            </view>
            <view class="time-item">
              <text class="time-value">{{ loveTimeDuration.seconds }}</text>
              <text class="time-unit">秒</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 宝宝纪念日 -->
      <view class="card baby-card" @click="showBabyAnimation">
        <view class="card-header">
          <text class="icon">👶</text>
          <text class="card-title">宝宝纪念日</text>
        </view>
        <view class="card-content">
          <text class="baby-name">墨轩</text>
          <text class="date">{{ formatBabyBirthDate }}</text>
          <text class="label">宝宝已经来到这个世界</text>
          <view class="time-row baby-time">
            <view class="time-item">
              <text class="time-value">{{ babyAge.years }}</text>
              <text class="time-unit">年</text>
            </view>
            <view class="time-item">
              <text class="time-value">{{ babyAge.months }}</text>
              <text class="time-unit">月</text>
            </view>
            <view class="time-item">
              <text class="time-value">{{ babyAge.days }}</text>
              <text class="time-unit">天</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 每日情话与宝宝相册组合区 -->
    <view class="quote-photo-section">
      <view class="section-header">
        <text class="section-title">💬 每日情话 & 👶 宝宝相册</text>
        <view class="refresh-btn" @click="refreshContent">
          <text>↻</text>
        </view>
      </view>
      
      <view class="combined-card">
        <!-- 情话区域 -->
        <view class="quote-area">
          <view class="heart-quote-icon">💖</view>
          <text class="quote-text">{{ dailyLoveQuote }}</text>
          <view class="quote-signature">
            <text class="signature-text"> -- to 我家糖宝</text>
            <text class="heart-icon">💗</text>
          </view>
          <text class="quote-date">{{ currentDate }}</text>
        </view>
        
        <!-- 宝宝相册区域 -->
        <view class="photo-area">
          <view class="photo-container" v-if="babyImageUrl">
            <image 
              :src="babyImageUrl" 
              class="baby-photo" 
              mode="aspectFit"
              @error="onImageError"
              @click="previewImage"
            ></image>
          </view>
          <view class="photo-placeholder" v-else>
            <text class="placeholder-text">正在加载宝宝照片...</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 图片预览 -->
    <view class="image-preview" v-if="previewImageVisible" @click="closePreview">
      <image 
        :src="previewImageUrl" 
        class="preview-image" 
        mode="aspectFit"
        @click.stop
      ></image>
      <view class="close-btn" @click="closePreview">✕</view>
    </view>
    
    <!-- 快捷入口 -->
    <view class="access-section">
      <text class="section-title">🚀 快捷入口</text>
      <scroll-view class="access-scroll" scroll-x="true">
        <view class="access-row">
          <navigator url="/pages/work/mytool/chat/index" class="access-item">
            <text class="access-icon">💬</text>
            <text class="access-text">聊天</text>
          </navigator>
          <navigator url="/pages/work/mytool/esp32/index" class="access-item">
            <text class="access-icon">🔧</text>
            <text class="access-text">ESP32控制</text>
          </navigator>
          <navigator url="/pages/work/mytool/job/index" class="access-item">
            <text class="access-icon">⏰</text>
            <text class="access-text">定时任务</text>
          </navigator>
          <navigator url="/pages/work/mytool/todo/webview" class="access-item">
            <text class="access-icon">📝</text>
            <text class="access-text">待办任务</text>
          </navigator>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { getDailyQuote, getBabyPhoto } from '@/api/mywork/webapi/index.js'
import config from '@/config'
import websocketManager from '@/utils/websocket.js'
import websocketHandler from '@/utils/websocketHandler.js'

export default {
  data() {
    return {
      loveStartDate: new Date('2017-04-01 00:00:00'),
      babyBirthDate: new Date('2025-05-08 18:59:00'),
      currentTime: new Date(),
      timer: null,
      dailyLoveQuote: '爱情是生活最好的提神剂，让每一天都充满阳光。',
      currentDate: '',
      showHearts: false,
      floatingHearts: [],
      babyImageUrl: '', // 宝宝图片URL
      defaultQuotes: [
        '爱情是生活最好的提神剂，让每一天都充满阳光。',
        '有你的日子，平凡也变得浪漫。',
        '最美的事不是下雨天，而是和你一起躲过雨的屋檐。',
        '我想和你一起慢慢变老，直到我们老得哪里也去不了。',
        '遇见你是命运的安排，成为朋友是我的选择，而爱上你是我无法控制的意外。',
        '我喜欢你，像风走了八千里，不问归期。',
        '愿所有的美好都能如期而至，包括我们的爱情。'
      ],
      previewImageVisible: false, // 图片预览可见性
      previewImageUrl: '' // 预览图片URL
    }
  },
  computed: {
    formatLoveStartDate() {
      return this.formatDate(this.loveStartDate)
    },
    formatBabyBirthDate() {
      return this.formatDateTime(this.babyBirthDate)
    },
    loveTimeDuration() {
      return this.calculateTimeDuration(this.loveStartDate, this.currentTime)
    },
    babyAge() {
      return this.calculateBabyAge(this.babyBirthDate, this.currentTime)
    }
  },
  onLoad() {
    // 注册WebSocket消息监听器
    this.registerWebSocketListener();
    // 注册通知消息监听器
    this.registerNotificationListener();
    // 初始化页面（不再初始化WebSocket连接）
    this.initializePage()
    // 页面加载时检查WebSocket状态，如果未连接则尝试连接
    this.checkAndReconnectWebSocket();
  },
  onShow() {
    this.startTimer()
  },
  onHide() {
    this.stopTimer()
  },
  beforeDestroy() {
    this.stopTimer()
    // 确保在页面销毁前关闭预览
    if (this.previewImageVisible) {
      uni.showTabBar({ animation: false });
    }
    // 不再在页面销毁时关闭WebSocket连接
    // this.closeWebSocket();
    // 移除全局事件监听
    uni.$off('websocket-message');
  },
  methods: {
    // 注册WebSocket消息监听器
    registerWebSocketListener() {
      // 监听WebSocket消息（除了通知类型的消息）
      uni.$on('websocket-message', (message) => {
        console.log('接收到WebSocket消息:', message);
        // 通知类型的消息已经在websocket.js中处理，这里不需要再处理
        if (message.type !== 'notification') {
          // 处理其他类型消息的逻辑可以在这里添加
        }
      });
    },
    
    // 注册通知消息监听器
    registerNotificationListener() {
      // 可以在这里添加额外的通知处理逻辑
    },
    
    // 处理通知类型消息（已移至websocket.js中处理，此处保留以确保向后兼容）
    handleNotificationMessage(message) {
      // 直接调用通知工具类显示通知，保持与定时任务一致的方式
      this.$notification.sendJobNotification(message.title, message.content);
    },
    
    initializePage() {
      this.updateCurrentTime()
      this.updateCurrentDate()
      this.startTimer()
      this.loadRandomQuote()
      this.loadRandomBabyImage() // 加载宝宝图片
    },
    startTimer() {
      if (this.timer) clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.currentTime = new Date()
      }, 1000)
    },
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    updateCurrentTime() {
      this.currentTime = new Date()
    },
    updateCurrentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      this.currentDate = `${year}年${month}月${day}日`
    },
    
    // 生成浮动爱心
    generateHearts(count, isBaby = false) {
      const hearts = []
      const symbols = isBaby ? ['👶', '🍼', '🧸', '💕'] : ['💖', '💗', '💓', '💞', '💕']
      const colors = isBaby ? ['#FFB6C1', '#87CEEB', '#98FB98'] : ['#FF69B4', '#FF1493', '#DC143C']
      
      for (let i = 0; i < count; i++) {
        hearts.push({
          x: Math.random() * uni.getSystemInfoSync().windowWidth,
          y: uni.getSystemInfoSync().windowHeight,
          size: Math.random() * 20 + 20,
          symbol: symbols[Math.floor(Math.random() * symbols.length)],
          color: colors[Math.floor(Math.random() * colors.length)],
          delay: Math.random() * 2,
          duration: Math.random() * 3 + 2,
          type: isBaby ? 'baby' : 'love'
        })
      }
      
      return hearts
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 计算恋爱时间差
    calculateTimeDuration(startDate, endDate) {
      const diff = endDate.getTime() - startDate.getTime()
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      
      return { days, hours, minutes, seconds }
    },
    
    // 计算宝宝年龄
    calculateBabyAge(birthDate, currentDate) {
      let years = currentDate.getFullYear() - birthDate.getFullYear()
      let months = currentDate.getMonth() - birthDate.getMonth()
      let days = currentDate.getDate() - birthDate.getDate()
      
      if (days < 0) {
        const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0)
        days += lastMonth.getDate(); months--
      }
      if (months < 0) { months += 12; years-- }
      
      return {
        years: Math.max(0, years),
        months: Math.max(0, months), 
        days: Math.max(0, days)
      }
    },
    // 从后端获取每日情话
    async loadRandomQuote() {
      try {
        console.log('开始获取每日情话...')
        const response = await getDailyQuote()
        console.log('情话接口响应:', response)
        this.dailyLoveQuote = response.data.message || '今日暂无情话'
        this.updateCurrentDate()
      } catch (error) {
        console.error('获取每日情话失败:', error)
        // 出错时使用默认情话
        const randomIndex = Math.floor(Math.random() * this.defaultQuotes.length)
        this.dailyLoveQuote = this.defaultQuotes[randomIndex]
        this.updateCurrentDate()
      }
    },
    
    // 从后端获取宝宝图片
    async loadRandomBabyImage() {
      try {
        console.log('开始获取宝宝图片...')
        const response = await getBabyPhoto()
        console.log('图片接口响应:', response)
        this.babyImageUrl = response.data.url || ''
      } catch (error) {
        console.error('获取宝宝图片失败:', error)
        // 出错时清空图片URL，显示占位符
        this.babyImageUrl = ''
        uni.showToast({
          title: '图片加载失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 图片加载失败
    onImageError() {
      uni.showToast({
        title: '图片加载失败',
        icon: 'none',
        duration: 2000
      });
      // 清空图片URL，显示占位符
      this.babyImageUrl = '';
    },
    
    // 图片预览功能
    previewImage() {
      if (this.babyImageUrl) {
        this.previewImageUrl = this.babyImageUrl;
        this.previewImageVisible = true;
        // 防止页面滚动
        uni.hideTabBar({ animation: false });
      }
    },
    
    // 关闭图片预览
    closePreview() {
      this.previewImageVisible = false;
      this.previewImageUrl = '';
      // 恢复页面滚动
      uni.showTabBar({ animation: false });
    },
    
    // 统一刷新内容
    async refreshContent() {
      await this.loadRandomQuote()
      await this.loadRandomBabyImage()
      uni.showToast({ title: '内容已刷新', icon: 'success', duration: 1500 })
    },
    
    // 初始化 WebSocket 连接（修改为检查连接状态）
    initWebSocket() {
      // 检查当前连接状态，只有未连接时才初始化
      const status = this.$websocket.getStatus();
      if (!status.isConnected) {
        this.$websocketHandler.initWebSocket({
          reconnectInterval: 3000,
          maxReconnectAttempts: 5,
          isSockJS: false,
          onConnect: () => {
            console.log('WebSocket 连接已建立');
            uni.showToast({
              title: '推送服务连接成功',
              icon: 'success',
              duration: 1000
            });
          },
          onMessage: (message) => {
            // 处理不同类型的消息
            if (message.type === 'notification' || message.type === 'job') {
              this.handleNotificationMessage(message);
            }
          },
          onError: (error) => {
            console.error('WebSocket 连接错误:', error);
            uni.showToast({
              title: '推送服务连接错误',
              icon: 'error',
              duration: 1000
            });
          },
          onClose: () => {
            console.log('WebSocket 连接已关闭');
          }
        });
      } else {
        console.log('WebSocket已连接，无需重新连接');
      }
    },
    
    // 检查并重连WebSocket
    checkAndReconnectWebSocket() {
      console.log('检查WebSocket连接状态');
      // 添加延迟确保页面完全加载后再检查连接
      setTimeout(() => {
        this.initWebSocket();
      }, 500);
    },
    
    // 绑定 WebSocket 事件（保留以保持兼容性，但不再使用）
    bindWebSocketEvents() {
      // 此方法已废弃，使用 websocketManager 替代
    },
    
    // 已废弃，现在直接在websocket消息处理中调用notification工具
    handleNotification(message) {
      // 保持方法存在以确保向后兼容
    },
    
    // 已废弃，现在直接在websocket消息处理中调用notification工具
    handleMessageNotification(message) {
      // 保持方法存在以确保向后兼容
    },
    
    // 关闭 WebSocket 连接
    closeWebSocket() {
      this.$websocketHandler.closeWebSocket();
    },
    
    // 爱心动画方法
    showLoveAnimation() {
      this.createHeartAnimation('love')
    },
    
    showBabyAnimation() {
      this.createHeartAnimation('baby')
    },
    
    createHeartAnimation(type) {
      this.showHearts = true
      this.floatingHearts = []
      
      const heartCount = 15 // 爱心数量
      const colors = type === 'love' ? [
        '#ff6b9d', '#ff8fab', '#ffa8cc', '#ffb3d6', '#ffc2e0'
      ] : [
        '#4fc3f7', '#64b5f6', '#81c784', '#aed581', '#90caf9'
      ]
      
      const symbols = type === 'love' ? ['♥', '❤️', '💕', '💖', '💗'] : ['👶', '⭐', '🌈', '🎆', '💙']
      
      for (let i = 0; i < heartCount; i++) {
        const heart = {
          x: Math.random() * (uni.getSystemInfoSync().windowWidth - 50),
          y: Math.random() * (uni.getSystemInfoSync().windowHeight - 200) + 100,
          size: Math.random() * 20 + 25, // 25-45px
          color: colors[Math.floor(Math.random() * colors.length)],
          symbol: symbols[Math.floor(Math.random() * symbols.length)],
          delay: Math.random() * 0.5,
          duration: Math.random() * 1 + 2, // 2-3秒
          type: type
        }
        this.floatingHearts.push(heart)
      }
      
      // 3秒后隐藏动画
      setTimeout(() => {
        this.showHearts = false
        this.floatingHearts = []
      }, 3500)
      
      // 显示提示
      const message = type === 'love' ? '♥ 爱意满满 ♥' : '👶 墨轩最可爱 👶'
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style src="./index.css"></style>